import {
	IEditViewController,
	IEditViewStore,
	IEditFormAbility,
	AuthUtil,
	deepCopy,
	IEditViewControllerParams,
	EditFormActionType,
	EditViewActionType,
	ICtrlActionResult,
	IEditViewAbility,
	IParam,
	IViewActionResult,
} from '@/core';
import { DEViewController } from './de-view-controller';

/**
 * 编辑视图控制器
 *
 * @export
 * @class EditViewController
 * @extends {DEViewController<T, S, A>}
 * @implements {IEditViewController}
 */
export class EditViewController
	extends DEViewController<EditViewActionType, IEditViewStore, IEditViewAbility>
	implements IEditViewController<IEditViewStore, IEditViewAbility>
{
	/**
	 * 处理视图初始化
	 *
	 * @protected
	 * @param {IEditViewControllerParams<EditViewActionType, IEditViewAbility>} params
	 * @memberof EditViewController
	 */
	protected processViewInit(
		params: IEditViewControllerParams<EditViewActionType, IEditViewAbility>
	) {
		super.processViewInit(params);
		Object.assign(this.store, { dataInfo: '' });
	}

	/**
	 * 获取表单能力
	 *
	 * @protected
	 * @return {*}  {(IEditFormAbility | undefined)}
	 * @memberof EditViewController
	 */
	protected getFormAbility(): IEditFormAbility | undefined {
		const form = this.model.ctrls.find(
			(ctrl: IParam) => ctrl.controlType === 'FORM'
		);
		if (form) {
			return this.getSubAbility<IEditFormAbility>(form.name);
		}
		return undefined;
	}

	/**
	 * 视图加载
	 *
	 * @param {IParam} [opts={}]
	 * @return {*}
	 * @memberof EditViewController
	 */
	public viewMounted(opts: IParam = {}) {
		super.viewMounted(opts);
		if (this.model.useDefaultLayout) {
			if (!this.isLoadDefault) {
				this.isLoadDefault = true;
				return;
			}
			this.load();
		} else {
			this.initLayout().then(() => {
				this.load();
			});
		}
	}

	/**
	 * 加载视图
	 *
	 * @param {IParam} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof EditViewController
	 */
	public load(args?: IParam): Promise<IViewActionResult> {
		const form = this.getFormAbility();
		if (form) {
			let action: 'loadDraft' | 'load' = 'loadDraft';
			if (
				this.model.entityCodeName &&
				this.store.context[this.model.entityCodeName.toLowerCase()]
			) {
				action = 'load';
			}
			return form[action](Object.assign(this.store.viewParams, args));
		} else {
			return Promise.reject({
				ok: false,
				data: null,
				rowData: { status: 500 },
			});
		}
	}

	/**
	 * 视图保存
	 *
	 * @param {IParam} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof EditViewController
	 */
	public save(args?: IParam): Promise<IViewActionResult> {
		return new Promise((resolve, reject) => {
			const form = this.getFormAbility();
			if (form) {
				const tempViewParams = deepCopy(this.store.viewParams);
				form
					.save(Object.assign(tempViewParams, args))
					.then((res: ICtrlActionResult) => {
						const data = res.data ? res.data : [];
						this.emit('viewDataSave', data);
						resolve({ ok: false, data: data, rowData: { status: 200 } });
					})
					.catch((error) => {
						this.emit('viewDataSave', []);
						reject({ ok: false, data: error, rowData: { status: 500 } });
					});
			} else {
				this.emit('viewDataSave', []);
				reject({ ok: false, data: [], rowData: { status: 500 } });
			}
		});
	}

	/**
	 * 处理表单行为
	 *
	 * @param {string} name 表单标识
	 * @param {FormActionType} action 表单行为
	 * @param {IParam[]} data 行为数据
	 * @memberof EditViewController
	 */
	public handleCtrlAction(
		name: string,
		action: EditFormActionType,
		data: IParam[]
	): void {
		super.handleCtrlAction(name, action, data);
		if (action === 'load' || action === 'loadDraft') {
			this.handleFormLoad(data);
		}
		if (action === 'save') {
			this.handleFormSave(data);
		}
		if (action === 'remove') {
			this.handleFormRemove(data);
		}
	}

	/**
	 * 处理表单加载完成
	 *
	 * @param {IParam[]} data 表单数据
	 * @memberof EditViewController
	 */
	protected async handleFormLoad(data: IParam[]) {
		await this.handleFormData(data);
		this.emit('viewDataLoaded', data);
	}

	/**
	 * 处理表单保存
	 *
	 * @param {IParam[]} data
	 * @memberof EditViewController
	 */
	protected async handleFormSave(data: IParam[]) {
		await this.handleFormData(data);
		this.emit('viewDataChange', data);
		this.emit('viewDataSave', data);
	}

	/**
	 * 处理表单删除
	 *
	 * @param {IParam[]} data
	 * @memberof EditViewController
	 */
	protected handleFormRemove(data: IParam[]) {
		this.emit('viewDataChange', data);
	}

	/**
	 * 处理表单数据
	 *
	 * @param {IParam[]} data
	 * @memberof EditViewController
	 */
	protected async handleFormData(data: IParam[]) {
		const arg = data[0];
		this.store.dataInfo = Object.is(arg.srfuf, '1')
			? this.model.majorPSAppDEField
				? arg[this.model.majorPSAppDEField.toLowerCase()]
				: arg.srfmajortext
			: App.ts('view.editview.newbuild', '新建');
		AuthUtil.calcToolbarItemState(
			Object.is(arg.srfuf, '0'),
			this.store.toolbarCtrls
		);
		await this.calcToolbarItemAuthState(arg);
	}
}
